﻿<%@ WebHandler Language="C#" Class="App_Gonglue" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
public class App_Gonglue : IHttpHandler, IRequiresSessionState
{
    readonly Users Users = new Users();
    readonly WinLog WinLog = new WinLog();
    string msg = string.Empty;
    public void ProcessRequest(HttpContext context)
    {
        CurrentContext = context;
        try
        {
            string action = context.Request.QueryString["action"].ToString();
          
            string token = string.Empty;
            string imgs = string.Empty;
            string title = string.Empty;
            string intro = string.Empty;
            string sids = string.Empty;
            string gids = string.Empty;
            
            string keyword = string.Empty;
            string cata = string.Empty;
            string pageindex = string.Empty;
            string pagesize = string.Empty;
            string udid = string.Empty;
            
            udid = GetQuery("udid");

            switch (action.ToLower())
            {
                case "upimg":
                    token = GetQuery("token");
                    UpImg(token, udid);
                    break;

                case "random":
                    GetRandom();
                    break;

                case "del":
                    token = GetQuery("token");
                    gids = GetQuery("gids");
                    Del(token, gids, udid);
                    break;
                case "create":
                    token = GetQuery("token");
                    sids = GetQuery("sids");
                    title = GetQuery("title");
                    cata = GetQuery("cata");
                    imgs = GetQuery("imgs");
                    intro = GetQuery("intro");
                    cata = GetQuery("cata", "1");
                    Create(title, token, imgs, intro, sids, cata, udid);
                    break;
                case "getlist":
                    keyword = GetQuery("keyword");
                    gids = GetQuery("gids");
                    sids = GetQuery("sids");
                    pageindex = GetQuery("pageindex", "1");
                    pagesize = GetQuery("pagesize", "10000");
                    token = GetQuery("token");
                    GetList(keyword, gids, sids, token, int.Parse(pageindex), int.Parse(pagesize));
                    break;
                case "getfavlist":
                    pageindex = GetQuery("pageindex", "1");
                    pagesize = GetQuery("pagesize", "10000");
                    token = GetQuery("token");
                    GetFavList(token, int.Parse(pageindex), int.Parse(pagesize));
                    break;
                case "addfav":
                    gids = GetQuery("gids");
                    token = GetQuery("token");
                    AddFav(gids, token, udid);

                    break;
                case "delfav":
                    gids = GetQuery("gids");
                    token = GetQuery("token");
                    DelFav(gids, token, udid);
                    break;
                case "shareme":

                    token = GetQuery("token");
                    ShareMeGonglue(token);
                    break;
                case "shareother":

                    token = GetQuery("token");
                    ShareOtherGonglue(token);
                    break;

            }
        }
        catch (Exception err)
        {
            msg = "{\"result\":\"error\",\"msg\":\"" + err.Message + "\"}";
        }
        finally
        {
            context.Response.Write(msg);
        }
    }
    public HttpContext CurrentContext;
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    readonly Gonglue Gonglue = new Gonglue();
    public string GetQuery(string name)
    {
        string res = string.Empty;
        if (CurrentContext.Request.QueryString[name] != null)
            res = CurrentContext.Request.QueryString[name].ToString();
        if (CurrentContext.Request[name] != null)
            res = CurrentContext.Request[name].ToString();
        return res;
    }


    public string GetQuery(string name, string defaultvalue)
    {
        string res = string.Empty;
        if (CurrentContext.Request.QueryString[name] != null)
            res = CurrentContext.Request.QueryString[name].ToString();
        if (string.IsNullOrEmpty(res)) res = defaultvalue;
        return res;
    }
    public string ShareMeGonglue(string token)
    {
        if ( string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (WinLog.CountByToday(token, "分享个人攻略积分") < 5)
                WinLog.Create(WinLog.GONGLUE_SHAREME, token, "分享个人攻略积分", "分享个人攻略积分");
            msg = "{\"result\":\"success\"}";
        }
        return msg;
    }

    public string ShareOtherGonglue(string token)
    {
        if (string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (WinLog.CountByToday(token, "分享他人攻略积分") < 5)
                WinLog.Create(WinLog.GONGLUE_SHAREOTHER, token, "分享他人攻略积分", "分享他人攻略积分");
            msg = "{\"result\":\"success\"}";
        }
        return msg;
    }
    public void UpImg(string token, string udid)
    {
        Guid t = new Guid(token);
        if (string.IsNullOrEmpty(token))//|| string.IsNullOrEmpty(udid)
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";

        }
        else
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            string sql = string.Format(" Token ='{0}'", token);
            int count = 0;
            dt = Users.GetList(sql, 1, 1, ref count);
            if (dt.Rows.Count > 0)
            {
                //**上传图片
                if (CurrentContext.Request.Files.Count > 0)
                {
                    //CurrentContext.Response.ContentType = "text/plain";
                    HttpFileCollection uploadedFiles = CurrentContext.Request.Files;
                    HttpPostedFile file = uploadedFiles[0];
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
                    filename += "_" + file.FileName + ".jpg";
                    string path = string.Format("/UserProfile/{0}/", dt.Rows[0]["Uid"].ToString());
                    if (!System.IO.Directory.Exists(CurrentContext.Server.MapPath(path)))
                        System.IO.Directory.CreateDirectory(CurrentContext.Server.MapPath(path));
                    file.SaveAs(CurrentContext.Server.MapPath(path) + filename);

                    msg = "{\"result\":\"success\",\"url\":\"" + string.Format("http://{0}{1}{2}", CurrentContext.Request.Url.Host, path, filename) + "\"}";
                }
                else
                {
                    msg = "{\"result\":\"error\",\"msg\":\"没有发现图片文件\"}";
                }
                ////WriteLog("postStr:" + postStr);

            }
            else
            {

                msg = "{\"result\":\"error\",\"msg\":\"无此用户信息\"}";
            }
        }

    }

    public void GetRandom()
    {
        string strSql = " select *,NewID() as random  from Gonglue order by random ";
        //string img
        System.Data.DataTable dtGonglue= Gomye.DataUtility.SqlRunner.DoSqlTable(strSql);
        string count = "1";
        if (dtGonglue.Rows.Count > 0)
        {
            msg = "{\"result\":\"success\",\"count\":" + count.ToString() + ",\"data\":[";

            string json_imgs = dtGonglue.Rows[0]["Imgs"].ToString().Split(',')[0];
            string json_intro = dtGonglue.Rows[0]["Intro"].ToString().Split(new string[] {"$$$$$$"},StringSplitOptions.None)[0];
            string title = dtGonglue.Rows[0]["Title"].ToString();
            if (json_intro.Length > 30)
            {
                json_intro = json_intro.Substring(0, 30) + "...";
            }
            if (title.Length > 8)
            {
                title = title.Substring(0, 8) + "...";
            }
            
            msg += "{\"gid\":" + dtGonglue.Rows[0]["Gid"].ToString() + ",";
            msg += "\"title\":\"" + title + "\",";
            
            msg += "\"imgs\":\"" + json_imgs + "\",";
            msg += "\"intro\":\"" + json_intro + "\",";
            msg += "\"token\":\"" + dtGonglue.Rows[0]["Token"].ToString() + "\",";
            msg += "\"uname\":\"" + dtGonglue.Rows[0]["UName"].ToString() + "\",";
            msg += "\"cata\":\"" + dtGonglue.Rows[0]["Cata"].ToString() + "\",";
            msg += "\"ctime\":\"" + dtGonglue.Rows[0]["CTime"].ToString() + "\",";
            msg += "\"url\":\"http://203.90.227.74/guideapp/guide.html?gid=" + dtGonglue.Rows[0]["Gid"].ToString() + "\",";
            msg += "\"pcurl\":\"http://203.90.227.74//guide/hide.shtml?gid=" + dtGonglue.Rows[0]["Gid"].ToString() + "\",";
            msg += "\"istop\":" + dtGonglue.Rows[0]["IsTop"].ToString() + "}";


            msg += "]}";

            //dtGonglue.Rows[0][];
        }
    }

    public void Create(string title,string token, string imgs, string intro, string sids,string cata,string udid)
    {
        if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(intro) || string.IsNullOrEmpty(sids))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            string str_cata = "普通攻略";
            if (cata == "2") str_cata = "活动攻略";
            if (string.IsNullOrEmpty(imgs))
            {
                int idx = 1;
                string upimgs = string.Empty;
                foreach (string tmpfile in CurrentContext.Request.Files)
                {
                    HttpPostedFile file = CurrentContext.Request.Files[tmpfile];
                    //CurrentContext.Response.ContentType = "text/plain";
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
                    filename += "_" + file.FileName + "_" + idx.ToString() + ".jpg";
                    string path = string.Format("/UserProfile/{0}/",token);
                    if (!System.IO.Directory.Exists(CurrentContext.Server.MapPath(path)))
                        System.IO.Directory.CreateDirectory(CurrentContext.Server.MapPath(path));
                    file.SaveAs(CurrentContext.Server.MapPath(path) + filename);
                    
                    upimgs+=string.Format("http://{0}{1}{2}", CurrentContext.Request.Url.Host, path, filename) + ",";
                    idx++;
                }
                if (!string.IsNullOrEmpty(upimgs))
                    imgs = upimgs.Substring(0, upimgs.Length - 1);
            }
            
            if (Gonglue.Create(token, title, imgs, sids, intro, str_cata))
            {
                msg = "{\"result\":\"success\",\"url\":\"http://203.90.227.74/\",\"msg\":\"操作成功200积分\"}";

                if (WinLog.CountByToday(token, "建立攻略获取积分")<5)
                    WinLog.Create(WinLog.GAME_ADDGL, token, "建立攻略获取积分", "建立攻略获取积分");
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"操作失败\"}";
        }
    }

    public void Del(string token, string gids, string udid)
    {
        if (string.IsNullOrEmpty(gids) || string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (Gonglue.Del(gids, token))
            {
                msg = "{\"result\":\"success\"}";
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"操作失败\"}";

        }
    }

    public void GetFavList(string token, int pageindex, int pagesize)
    {
        string sql = string.Empty;
        string errmsg = string.Empty;

        string strwhere = " 1=1 ";
       
        if (!string.IsNullOrEmpty(token))
            strwhere += string.Format(" and Gid in (Select Gid from Users_FavGonglue where Uid in (Select Uid from Users where Token = '{0}'))", token);


        int count = 0;

        System.Data.DataTable dt = Gonglue.GetList(strwhere, pageindex, pagesize, ref count);

        if (string.IsNullOrEmpty(errmsg))
        {
            msg = "{\"result\":\"success\",\"count\":" + count.ToString() + ",\"data\":[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                System.Data.DataRow dr = dt.Rows[i];
                string json_store = "\"" + dr["Stores"].ToString().Replace(",", "\",\"") + "\"";
                string json_imgs = "\"" + dr["Imgs"].ToString().Replace(",", "\",\"") + "\"";
                string json_intro = "\"" + JSON.CoatnvertJson(dr["Intro"].ToString()).Replace("$$$$$$", "\",\"") + "\"";

                msg += "{\"gid\":" + dr["Gid"].ToString() + ",";

                msg += "\"stores\":[" + json_store + "],"; // \"维迪莎咖啡\",\"汉堡王\",\"肯德基\"
                msg += "\"sids\":[" + dr["Sids"].ToString() + "],";

                msg += "\"imgs\":[" + json_imgs + "],";
                msg += "\"title\":\"" + dr["Title"].ToString() + "\",";
                msg += "\"icon\":\"" + dr["ICon"].ToString() + "\",";
                msg += "\"intro\":[" + json_intro + "],";
                msg += "\"token\":\"" + dr["Token"].ToString() + "\",";
                msg += "\"uname\":\"" + dr["UName"].ToString() + "\",";
                msg += "\"cata\":\"" + dr["Cata"].ToString() + "\",";
                msg += "\"ctime\":\"" + dr["CTime"].ToString() + "\",";

                msg += "\"url\":\"http://203.90.227.74/guideapp/guide.html?gid=" + dr["Gid"].ToString() + "\",";
                msg += "\"pcurl\":\"http://203.90.227.74//guide/hide.shtml?gid=" + dr["Gid"].ToString() + "\",";
                msg += "\"istop\":" + dr["IsTop"].ToString() + "}";
                if (i < dt.Rows.Count - 1)
                    msg += ",";
            }
            msg += "]}";

        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"" + errmsg + "\"}";

    }
    
    public void GetList(string keyword, string gids, string sids, string token, int pageindex, int pagesize)
    {
        string sql = string.Empty;
        string errmsg = string.Empty;
        
        string strwhere = " 1=1 ";
        if (!string.IsNullOrEmpty(keyword))
            strwhere += string.Format(" and Title like '%{0}%'", keyword);
        if (!string.IsNullOrEmpty(sids))//**
        {
           // strwhere += string.Format(" and Content_Entity.ContentId in ({0})", sids);
        }
        if (!string.IsNullOrEmpty(gids))
            strwhere += string.Format(" and Gid in ({0})", gids);
        if (!string.IsNullOrEmpty(token))
            strwhere += string.Format(" and Token = '{0}'", token);
        
        
        int count = 0;
        string tempSql = "";
        System.Data.DataTable dt = Gonglue.GetList(strwhere, pageindex, pagesize, ref count);

        if (string.IsNullOrEmpty(errmsg))
        {
            msg = "{\"result\":\"success\",\"count\":" + count.ToString() + ",\"data\":[";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                System.Data.DataRow dr = dt.Rows[i];
                string json_store = "\"" + dr["Stores"].ToString().Replace(",", "\",\"") + "\"";
                string json_imgs = "\"" + dr["Imgs"].ToString().Replace(",", "\",\"") + "\"";
                string json_intro = "\"" + JSON.CoatnvertJson(dr["Intro"].ToString()).Replace("&&&&&&", "\",\"") + "\"";
               
                msg += "{\"gid\":" + dr["Gid"].ToString() + ",";
               
                msg += "\"stores\":["+json_store +"],"; // \"维迪莎咖啡\",\"汉堡王\",\"肯德基\"
                msg += "\"sids\":[" + dr["Sids"].ToString() + "],";
                
                msg += "\"imgs\":[" + json_imgs + "],";
                msg += "\"title\":\"" + dr["Title"].ToString() + "\",";
                msg += "\"icon\":\"" + dr["ICon"].ToString() + "\",";
                msg += "\"intro\":[" + json_intro+ "],";
                msg += "\"token\":\"" + dr["Token"].ToString() + "\",";
                msg += "\"uname\":\"" + dr["UName"].ToString() + "\",";
                msg += "\"cata\":\"" + dr["Cata"].ToString() + "\",";
                msg += "\"ctime\":\"" + dr["CTime"].ToString() + "\",";

                msg += "\"url\":\"http://203.90.227.74/guideapp/guide.html?gid=" + dr["Gid"].ToString() + "\",";
                msg += "\"pcurl\":\"http://203.90.227.74//guide/hide.shtml?gid=" + dr["Gid"].ToString() + "\",";
                msg += "\"istop\":" + dr["IsTop"].ToString() + "}";
                if (i <dt.Rows.Count-1)
                    msg += ",";
            }
            msg += "]}";

        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"" + errmsg + "\"}";

    }

    public void AddFav(string gids, string token, string udid)
    {
        if (string.IsNullOrEmpty(gids))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (Gonglue.ExistFav(gids, token))
               msg = "{\"result\":\"error\",\"msg\":\"攻略已经被收藏过了\"}";
            else
            {
                if (Gonglue.AddFav(gids, token))//
                {
                    msg = "{\"result\":\"success\",\"msg\":\"收藏成功\"}";
                    if (WinLog.CountByToday(token, "收藏攻略获取积分") < 10)
                        WinLog.Create(WinLog.GONGLUE_FAV, token, "收藏攻略获取积分", "收藏攻略获取积分");
                }
                else
                    msg = "{\"result\":\"error\",\"msg\":\"操作失败\"}";
            }

        }
    }

    public void DelFav(string gids, string token, string udid)
    {
        if (string.IsNullOrEmpty(gids) || string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (Gonglue.DelFav(gids,token))
            {
                msg = "{\"result\":\"success\",\"msg\":\"删除收藏成功\"}";
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"操作失败\"}";

        }
    }
}
